<?php

namespace app\admin\model;

use think\Model;

/**
 * Activity
 */
class Topic extends Model
{
    // 表名
    protected $name = 'topic_topic';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'topicTags', 'extraTagsArray'
    ];

    protected static function onAfterInsert($model): void
    {
        if (is_null($model->weigh)) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getExtraTagsAttr($value, $row): array
    {
        if ($row['extra_tag'] === '' || $row['extra_tag'] === null) return [];
        if (!is_array($row['extra_tag'])) {
            return explode(',', $row['extra_tag']);
        }
        return $row['extra_tag'];
    }

    public function getTopicTagsAttr($value, $row): array
    {
        return [
            'tag_name' => \app\admin\model\TopicTags::whereIn('id', $row['special_tags_ids'])->column('tag_name'),
        ];
    }

    public function getTopicTagsIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setTopicTagsIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getContentAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }
    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\User::class, 'user_id', 'id');
    }
}